package com.lzy.cloud.search.client.service.impl;

import com.lzy.cloud.search.client.entity.EsIndex;
import com.lzy.cloud.search.client.service.UpdateDocmentService;
import com.lzy.cloud.search.client.util.EsClient;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.update.UpdateRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

/**
 * 更新文档
 * Created by http://quanke.name on 2017/11/10.
 */
@Slf4j
@Service
public class UpdateDocmentServiceImpl implements UpdateDocmentService {
    @Autowired
    private EsClient client;

    /**
     * 使用 UpdateRequest 操作
     *
     * @
     */
    @Override
    public void forUpdateRequest(EsIndex esIndex) {
        try {
            UpdateRequest updateRequest = new UpdateRequest();
            updateRequest.index("twitter");
            updateRequest.type("tweet");
            updateRequest.id("2");
            updateRequest.doc(jsonBuilder()
                    .startObject()
                    .field("user", "http://quanke.name")
                    .endObject());
            client.getConnection().update(updateRequest).get();
        }catch (Exception e){
            log.error("更新文档出错"+e.getMessage());
        }
    }

    /**
     * 使用prepareUpdate
     *
     * @
     */
    public void testForPrepareUpdate() {
//        client.prepareUpdate("twitter", "tweet", "2")
//                .setScript(new Script(ScriptType.INLINE, "ctx._source.user = \"quanke.name\"", null, null))
//                .get();

//        client.prepareUpdate("twitter", "tweet", "2")
//                .setDoc(jsonBuilder()
//                        .startObject()
//                        .field("user", "quanke.name")
//                        .endObject())
//                .get();

    }

}
